package ahblue.cn.tanzi.ui.person;

import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;

import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.jmessage.im.ui.SettingActivity;
import ahblue.cn.tanzi.jmessage.im.util.DialogCreator;
import ahblue.cn.tanzi.jmessage.im.util.ToastUtil;
import ahblue.cn.tanzi.model.VersionInfo;
import ahblue.cn.tanzi.model.user.LoginResultModel;
import ahblue.cn.tanzi.util.CleanDataUtils;
import ahblue.cn.tanzi.util.SharePreferenceUtil;
import ahblue.cn.tanzi.view.UpdateProgressbarWindow;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PersonSettingActivity extends AppCompatActivity {

    private static final int DOWNLOAD_HANDLE = 101;

    @BindView(R.id.tv_cache_size)
    TextView tvCacheSize;

    private Dialog mDialog;
    private int mWidth;
    private String userInfo = "";
    private SharePreferenceUtil sharePreferenceUtil;
    private DownloadChangeObserver downloadObserver;
    private ExecutorService cachedThreadPool;
    private UpdateProgressbarWindow progressbarWindow;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    private VersionInfo mVersionInfo;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        sharePreferenceUtil = new SharePreferenceUtil(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_setting);
        ButterKnife.bind(this);
        String totalCache = "";
        try {
            totalCache = CleanDataUtils.getTotalCacheSize(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvCacheSize.setText(totalCache);

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        mWidth = dm.widthPixels;

        cachedThreadPool = Executors.newCachedThreadPool();
    }

    @OnClick({R.id.btn_back,R.id.ll_user_and_security,R.id.ll_message_setting,R.id.ll_privacy_setting,
                R.id.ll_check_update,R.id.ll_clear_cache})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.ll_user_and_security:
                intent = new Intent(getApplicationContext(),UserAndSecurityActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_message_setting:
                intent = new Intent(getApplicationContext(),SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_privacy_setting:
                intent = new Intent(getApplicationContext(),PrivacySettingActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_check_update:
                getVersion();
                break;
            case R.id.ll_clear_cache:
                userInfo = LoginResultModel.getUserModel(this);
                mDialog = DialogCreator.createExitGroupDialog(this, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (view.getId()) {
                            case R.id.jmui_cancel_btn:
                                mDialog.cancel();
                                break;
                            case R.id.jmui_commit_btn:
                                mDialog.cancel();
                                try {
                                    CleanDataUtils.clearAllCache(getApplicationContext());
                                    String size = CleanDataUtils.getTotalCacheSize(getApplicationContext());
                                    tvCacheSize.setText(size);
                                    ToastUtil.shortToast(getApplicationContext(),"缓存清理完成");
                                }catch (Exception e){
                                    ToastUtil.shortToast(getApplicationContext(),"缓存清理失败");
                                }

                                break;
                        }
                    }
                });
                mDialog.getWindow().setLayout((int) (0.8 * mWidth), WindowManager.LayoutParams.WRAP_CONTENT);
                mDialog.show();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        if (!TextUtils.isEmpty(userInfo)){
            LoginResultModel.putUserModel(this,userInfo);
        }
        if (downloadObserver != null) {
            getContentResolver().unregisterContentObserver(downloadObserver);
        }

        super.onDestroy();

    }


    private void getVersion(){
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getVersionInfo(new ApiCallback<VersionInfo>() {
            @Override
            public void onSuccess(VersionInfo data) {

                if (data == null || TextUtils.isEmpty(data.getDownloadUrl())){
                    ToastUtil.shortToast(PersonSettingActivity.this,"获取下载地址失败");
                    return;
                }
                if (!getVersionCode().equals(data.getVersion())){
                    progressbarWindow = new UpdateProgressbarWindow(PersonSettingActivity.this, data);
                    progressbarWindow.showAtLocation(PersonSettingActivity.this.findViewById(R.id.ll_person_setting_activity), Gravity.CENTER, 0, 0);
                    cachedThreadPool.execute(new DownLoadTask(progressbarWindow.getProgressBar(), data));
                }
            }

            @Override
            public void onFailed(String errorMsg) {
                ToastUtil.shortToast(PersonSettingActivity.this,"获取下载地址失败");
            }
        });

    }



    /**
     * 得到应用程序的版本号
     */
    private String getVersionCode() {
        // 用来管理手机的APK
        PackageManager pm = getPackageManager();
        try {
            // 得到知道APK的功能清单文件
            PackageInfo info = pm.getPackageInfo(getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }

    }



    public class DownLoadTask implements Runnable {
        private NumberProgressBar progressBar;
        private VersionInfo downLoad;

        public DownLoadTask(NumberProgressBar progressBar, VersionInfo download) {
            this.progressBar = progressBar;
            this.downLoad = download;
        }

        @Override
        public void run() {
            downLoadFile(downLoad);
        }

        private void downLoadFile(VersionInfo downLoad) {
            //1.得到下载对象
            DownloadManager dowanloadmanager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            //2.创建下载请求对象，并且把下载的地址放进去
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downLoad.getDownloadUrl()));
            //3.给下载的文件指定路径
            request.setDestinationInExternalFilesDir(PersonSettingActivity.this, Environment.DIRECTORY_DOWNLOADS, "tanzi_" + downLoad.getVersion() + ".apk");
            //4.设置显示在文件下载Notification（通知栏）中显示的文字。6.0的手机Description不显示
            request.setTitle("藏宝鼠");
            request.setDescription("藏宝鼠" + downLoad.getVersion());
            //5更改服务器返回的minetype为android包类型
            request.setMimeType("application/vnd.android.package-archive");
            //6.设置在什么连接状态下执行下载操作
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
            //7. 设置为可被媒体扫描器找到
            request.allowScanningByMediaScanner();
            //8. 设置为可见和可管理
            request.setVisibleInDownloadsUi(true);

            long lastDownloadId = dowanloadmanager.enqueue(request);
            downLoad.setLastDownLoadId(lastDownloadId);

            sharePreferenceUtil.setDownloadId(lastDownloadId);
            //10.采用内容观察者模式实现进度
            downloadObserver = new DownloadChangeObserver(null, progressBar, downLoad);
            getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
        }
    }


    //用于显示下载进度
    class DownloadChangeObserver extends ContentObserver {
        private NumberProgressBar progressBar;
        private VersionInfo downLoad;


        public DownloadChangeObserver(Handler handler, NumberProgressBar progressBar, VersionInfo download) {
            super(handler);
            this.progressBar = progressBar;
            this.downLoad = download;
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downLoad.getLastDownLoadId());
            DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                final int progress = Math.round(percent * 100);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setProgress(progress);
                        if (progress == 100) {
                            install(PersonSettingActivity.this, downLoad.getLastDownLoadId());
                            if (progressbarWindow != null && progressbarWindow.isShowing()) {
                                progressbarWindow.dismiss();
                            }
                        }
                    }
                });

            }
        }
    }


    //安装
    private void install(Context context, long downloadId){
        Intent install = new Intent(Intent.ACTION_VIEW);
        File apkFile = queryDownloadedApk(context, downloadId);
        if (apkFile != null){
            if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {

                Uri contentUri = FileProvider.getUriForFile(context,"ahblue.cn.tanzi.fileprovider",apkFile);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(contentUri,"application/vnd.android.package-archive");
                context.startActivity(install);
            }else{
                install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);
            }

        }

    }

    //通过downLoadId查询下载的apk，解决6.0以后安装的问题
    public static File queryDownloadedApk(Context context, long downloadId) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (downloadId != -1) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }
                cur.close();
            }
        }
        return targetApkFile;
    }
}
